package org.goldfish.distributed_framework.registry.handlers;

import com.sun.net.httpserver.HttpExchange;
import org.goldfish.distributed_framework.registry.ServiceRegistry;
import org.goldfish.distributed_framework.registry.utils.FormParser;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RegisterHandler extends BaseHandler {
    public RegisterHandler(String pattern) {
        super(pattern); // 设置该处理器的 path 模式
    }

    @Override
    protected void doHandle(HttpExchange exchange, String extractedBody) throws IOException {
        if (!"POST".equals(exchange.getRequestMethod())) {
            sendResponse(exchange, 405, "Method Not Allowed");
            return;
        }

        Map<String, String> params = FormParser.parse(extractedBody);
        System.out.println("解析参数: " + params);

        String service = params.get("service");
        String address = params.get("address");

        if (service == null || address == null) {
            sendResponse(exchange, 400, "Missing parameter[s]"
                    + ((service == null) ? "service," : "")
                    + ((address == null) ? "address" : "")
            );

            return;
        }

        // 注册逻辑
        ServiceRegistry.register(service, address);
        sendResponse(exchange, 200, "Service registered: " + service + " at " + address);
    }
}
